package com.maxbill.fxui.root;

import com.maxbill.MainApplication;
import com.maxbill.base.service.DataService;
import com.maxbill.fxui.mian.MainWindow;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.application.Preloader;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.SpringApplication;
import org.springframework.util.StringUtils;

import static com.maxbill.fxui.util.CommonConstant.*;
import static com.maxbill.fxui.util.DesktopObjects.*;


/**
 * 根窗口
 *
 * @author MaxBill
 * @date 2019/07/06
 */
@Log4j2
public class RootWindow extends Application {

    BooleanProperty ready = new SimpleBooleanProperty(false);

    @Override
    public void init() {
        //启动扫描服务
        long initTimeStart = System.currentTimeMillis();
        context = SpringApplication.run(MainApplication.class);
        if (null != context) {
            context.getBean(DataService.class).initSystemData();
        } else {
            return;
        }
        long initTimeEnd = System.currentTimeMillis();
        log.info("系统初始化成功,耗时{}ms", (initTimeEnd - initTimeStart));
    }

    @Override
    public void start(Stage winStage) {

//        new Thread(longTask()).start();
//        ready.addListener((observable, oldValue, newValue) -> {
//            if(Boolean.TRUE.equals(newValue)){
//                Platform.runLater(winStage::show);
//            }
//        });

        //设置窗口信息
        winStage.centerOnScreen();
        winStage.setTitle(APP_NAME);
        winStage.setAlwaysOnTop(false);
        winStage.initStyle(StageStyle.TRANSPARENT);
        winStage.getIcons().add(new Image(APP_ICON));
        mainWin = MainWindow.getMainWindow();
        Scene scene = new Scene(mainWin, MIN_W, MIN_H);
        winStage.setScene(scene);

        winStage.show();
        rootWin = winStage;
        rootListener();
        rootKeyboard();
        MainWindow.mainListener();
    }

    /**
     * 监听窗口属性事件
     */
    private void rootListener() {
        rootWin.xProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
            if (newValue != null && !IS_MAX) {
                WIN_X = newValue.doubleValue();
            }
        });
        rootWin.yProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
            if (newValue != null && !IS_MAX) {
                WIN_Y = newValue.doubleValue();
            }
        });
        rootWin.widthProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
            if (newValue != null && !IS_MAX) {
                WIN_W = newValue.doubleValue();
            }
        });
        rootWin.heightProperty().addListener((ObservableValue<? extends Number> observable, Number oldValue, Number newValue) -> {
            if (newValue != null && !IS_MAX) {
                WIN_H = newValue.doubleValue();
            }
        });
    }

    /**
     * 监听窗口键盘事件
     */
    private void rootKeyboard() {
        rootWin.getScene().setOnKeyPressed(event -> {
            System.out.println("setOnKeyPressed");
            System.out.println("event.getCode()=" + event.getCode());
            KEY_CODE = KEY_CODE.concat(event.getCode().toString());
        });
        rootWin.getScene().setOnKeyReleased(event -> {
            System.out.println("setOnKeyReleased:" + KEY_CODE);
            if (!StringUtils.isEmpty(KEY_CODE)) {
                switch (KEY_CODE) {
                    case "CONTROLF":
                        IS_FULL = true;
                        rootWin.setFullScreen(true);
                        break;
                    case "ESC":
                        IS_FULL = false;
                        break;
                    default:
                        break;
                }
            }
            KEY_CODE = "";
        });
    }


    private Task longTask() {
        return new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                //模拟准备耗时数据
                int max = 10;
                for (int i = 1; i <= max; i++) {
                    Thread.sleep(2000);
                    // 发送进程给预加载器主要通过Application中的notifyPreloader（PreloaderNotification）方法
                    Preloader.ProgressNotification notification = new Preloader.ProgressNotification(((double) i) / max);
                    notifyPreloader(notification);
                }
                // 这里数据已经准备好了
                // 在隐藏预加载程序之前防止应用程序过早退出
                ready.setValue(Boolean.TRUE);

                notifyPreloader(new Preloader.StateChangeNotification(
                        Preloader.StateChangeNotification.Type.BEFORE_START));
                return null;
            }
        };
    }

}
